<script setup lang='ts'>
import { reactive, onMounted, ref, defineAsyncComponent, nextTick,onUnmounted } from "vue"
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import { accountPageApiPost, accountDeleteApiDelete, accountDisableOrEnableApiPut, roleListApiPost, accountDetailApiGet, accountRelationRoleListApiPost } from "@/api/userMangement"
import useInstance from '@/hooks/useInstance';
// import { useConfig } from "./config"
const addEdit = defineAsyncComponent(() => import("./components/addEdit.vue"))
const rolePer = defineAsyncComponent(() => import("./components/rolePer.vue"))
const detailRef = ref<{ show: (title: string, row?: any) => void }>()
defineOptions({
    name: 'userTable'
})
const { global } = useInstance();
const isDisable: any = {
    N: "禁用",
    Y: "启用"
}
const { detailData } = useConfig()
const userAddEditRef = ref<{ show: (type: string, row?: any) => void }>()
const rolePerRef = ref<{ show: (type: string, row?: any, list?: any) => void }>()
const listSearch = reactive({
    pageNum: 1,
    pageSize: 20,
    condition: {
        username: null,
        nickname: null,
        mobile: null,
        email: null,
        enabled: null
    },
      orders: ["created_time desc"],
});
const pageParams = reactive({
    total: 0,
    loadIng: false,
    tableData: [],
    roleList: [],
    tableHeight: 500
})
onMounted(() => {
    getData('search')
    getRoleList()
    nextTick(() => {
        const dom = document.querySelector(".card-2") as any
        pageParams.tableHeight = dom.offsetHeight - 60
    })
      window.addEventListener("resize", () => {
        resizeWin()
    })
})
onUnmounted(() => {
  window.removeEventListener("resize", resizeWin)
})
const resizeWin = () => {
    const dom = document.querySelector(".card-2") as any
    pageParams.tableHeight = dom.offsetHeight - 60
}
const getRoleList = async () => {
    const res = await roleListApiPost({
        id: null,
        code: null,
        name: null
    })
    if (res.code == 20000) {
        pageParams.roleList = res.data
    }
}
const addEditBtn = (type: string, row?: any) => {
    if (type === "add") {
        userAddEditRef.value?.show('add')
    } else {
        userAddEditRef.value?.show('edit', JSON.parse(JSON.stringify(row)))
    }
}
const getData = async (type: string) => {
    pageParams.loadIng = true
    if (type === 'reset') {
        listSearch.pageNum = 1
        listSearch.pageSize = 20
        listSearch.condition.username = null
        listSearch.condition.nickname = null
        listSearch.condition.mobile = null
        listSearch.condition.email = null
        listSearch.condition.enabled = null
    }
    try {
        const res = await accountPageApiPost(listSearch)
        if (res.code == 20000) {
            pageParams.tableData = res.data.records
            pageParams.total = res.data.total
            pageParams.loadIng = false

            nextTick(() => {
                const dom = document.querySelector(".card-2") as any
                pageParams.tableHeight = dom.offsetHeight - 60
            })
        }
    } catch (error) {
        console.log("accountPageApiPost");
    }


}
const handleSizeChange = (size: number) => {
    listSearch.pageSize = size
    getData('search')
}
const handleCurrentChange = (page: number) => {
    listSearch.pageNum = page
    getData('search')
}
const delBtn = async (row: any) => {
    const flag = await global.$myconfirm(`是否确定删除该数据？`)
    if (flag) {
        const res = await accountDeleteApiDelete({ id: row.id })
        console.log(res.data);
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "数据删除成功"
            })
            getData('search')
        } else {
            ElMessage({
                type: "error",
                message: "数据删除失败"
            })
        }

    }
}
const roleBtn = async (row: any) => {
    console.log(row);
    try {
        const res = await accountRelationRoleListApiPost({ accountId: row.id })
        if (res.code == 20000) {
            const arr = res.data.map(it => it.roleCode)

            rolePerRef.value?.show('add', row, arr)
        }
    } catch (error) {
        ElMessage({
            type: "error",
            message: "数据请求失败"
        })
    }

}
const bthDisableAndUse = async (row: any) => {
    //accountDisableOrEnableApiPut // 如何判断员工的状态
    const str = row.enabled == "Y" ? "确定禁用该员工账号？" : "确定启用该员工账号"
    const flag = await global.$myconfirm(`${str}`)
    if (flag) {
        const res = await accountDisableOrEnableApiPut({ id: row.id, enabled: row.enabled == "Y" ? "N" : "Y" })
        console.log(res.data);
        if (res.code == 20000) {
            ElMessage({
                type: "success",
                message: "数据修改成功"
            })
            getData('search')
        } else {
            ElMessage({
                type: "error",
                message: "数据修改失败"
            })
        }

    }
}

const detailBtn = async (row: any) => {
    try {
        const res = await accountDetailApiGet({ id: row.id })
        if (res.code != 20000) return
        detailData.value = detailData.value.map(item => {
            if (item.prop == "isDisable") {
                return {
                    ...item,
                    value: isDisable[res.data[item.prop]]

                }
            } else {
                return {
                    ...item,
                    value: res.data[item.prop]
                }
            }
        })
        detailRef.value.dialogBasic.height = 450
        detailRef.value?.show('edit')
    } catch (error) {

    }
}
</script>

<template>
    <div class="user-table-con">
        <el-card shadow="never">
            <div class="list-search">
                <el-form :inline="true" :model="listSearch" class="demo-form-inline">
                    <el-row :gutter="20">
                        <el-col :span="6">
                            <el-form-item label="用户账号">
                                <el-input v-model="listSearch.condition.username" placeholder="请输入用户账号"
                                    @keyup.enter.native="getData('search')" @clear="getData('search')" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="用户姓名">
                                <el-input v-model="listSearch.condition.nickname" placeholder="请输入用户姓名"
                                    @keyup.enter.native="getData('search')" @clear="getData('search')" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="用户邮箱">
                                <el-input v-model="listSearch.condition.email" placeholder="请输入用户邮箱"
                                    @keyup.enter.native="getData('search')" @clear="getData('search')" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="手机号码">
                                <el-input v-model="listSearch.condition.mobile" placeholder="请输入手机号"
                                    @keyup.enter.native="getData('search')" @clear="getData('search')" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="用户状态">
                                <el-select v-model="listSearch.condition.enabled" @change="getData('search')"
                                    placeholder="请选择用户状态" clearable >
                                    <el-option label="启用" value="Y" />
                                    <el-option label="禁用" value="N" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="list-operate">
                <div class="operate-left">
                    <el-button :icon="Plus" v-permission="'ACCOUNT:CREATE-EDIT'" type="primary"
                        @click="addEditBtn('add')">新建</el-button>
                </div>
                <div class="operate-right">
                    <el-button :icon="Search" type="primary" @click="getData">查询</el-button>
                    <el-button :icon="Refresh" @click="getData('reset')">重置</el-button>
                </div>
            </div>
        </el-card>
        <el-card shadow="never" style="margin-top: 10px;" class="card-2" >
            <div class="list-table">
          
                <div>
                    <el-table :data="pageParams.tableData" :height="pageParams.tableHeight" stripe
                        v-loading="pageParams.loadIng"
                        :header-cell-style="{ fontSize: '14px', backgroundColor: '#FFF2F3F5', color: '#333' }">
                        <el-table-column prop="username" label="用户账号" show-overflow-tooltip align="center"
                            width="200" />
                        <el-table-column prop="nickname" label="用户姓名" show-overflow-tooltip align="center"
                            width="200" />
                        <el-table-column prop="mobile" label="手机号" show-overflow-tooltip align="center" width="200" />
                        <el-table-column prop="email" label="邮箱" show-overflow-tooltip align="center" width="200" />
                        <el-table-column prop="enabled" label="用户状态" show-overflow-tooltip align="center" width="200">
                            <template #default="scope">
                                {{ isDisable[scope.row?.enabled] }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="provinceName" label="所在地-省" show-overflow-tooltip align="center"
                            width="200" />
                        <el-table-column prop="cityName" label="所在地-市" show-overflow-tooltip align="center"
                            width="200" />
                        <el-table-column prop="adress" label="详细地址" show-overflow-tooltip align="center" width="200" />
                        <el-table-column prop="blurb" label="用户简介" show-overflow-tooltip align="center" />


                        <el-table-column fixed="right" label="操作" align="center" width="250">
                            <template #default="scope">
                                <el-button type="primary" size="small" link @click="detailBtn(scope.row)"
                                    v-permission="'ACCOUNT:DETAIL'">详情</el-button>
                                <el-button type="primary" size="small" link v-permission="'ACCOUNT:CREATE-EDIT'"
                                    @click="addEditBtn('edit', scope.row)">编辑</el-button>
                                <el-button type="primary" v-permission="'ACCOUNT:ENABLE'" size="small" link
                                    @click="bthDisableAndUse(scope.row)"> {{ scope.row.enabled == "Y" ? "禁用" : "启用" }}
                                </el-button>
                                <el-button type="danger" v-permission="'ACCOUNT:DELETE'" size="small" link
                                    @click="delBtn(scope.row)">删除</el-button>
                                <el-button type="success" size="small" link @click="roleBtn(scope.row)">角色分配</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <div class="demo-pagination-block">
                    <el-pagination v-model:currentPage="listSearch.pageNum" v-model:page-size="listSearch.pageSize"
                        size="small" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="pageParams.total" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </el-card>

        <addEdit ref="userAddEditRef" @refresh="getData('reset')"></addEdit>
        <rolePer ref="rolePerRef" :roleList="pageParams.roleList" @refresh="getData('reset')"></rolePer>
        <FormDetail :detailData="detailData" ref="detailRef"></FormDetail>
    </div>
</template>

<style lang='scss' scoped>
.user-table-con {
    display: flex;
    // height: 100%;
    flex-direction: column;
    .card-2 {
        flex-grow: 1;
    }
}

.list-operate {
    display: flex;

    .operate-left {
        width: 250px;
    }

    .operate-right {
        flex: 1;
        display: flex;
        justify-content: end;
    }
}



.demo-pagination-block {
    display: flex;
    margin-top: 10px;
    justify-content: end;
}
</style>
